package com.axend.aerosense.user.viewmodel;

import android.app.Activity;
import android.app.Application;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.bean.TipsBean;
import com.axend.aerosense.common.bean.UpdataPasswordBean;
import com.axend.aerosense.common.bean.VCodeLoginBean;
import com.axend.aerosense.common.bean.VerificationBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.ui.LoadingDialog;
import com.axend.aerosense.common.util.CheckUtil;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.ProgressDialogCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.axend.aerosense.user.R;

import io.reactivex.disposables.Disposable;

public class AdpterFragmentViewModel extends AndroidViewModel {
    public MutableLiveData<String> vCode = new MutableLiveData<>("");
    public MutableLiveData<String> password = new MutableLiveData<>("");
    public String initTimeString = "";
    /**
     * 是都是密码可见状态
     */
    public MutableLiveData<Boolean> isEyeOpen = new MutableLiveData<>(true);
    public MutableLiveData<String> phoneNum = new MutableLiveData<>("");
    public String title;
    public boolean passwordViewVisable = false;
    public String buttonText;
    private Disposable disposable;
    public MutableLiveData<String> timeTitle = new MutableLiveData<>("");
    private CountDownTimer downTimer = null;


    public AdpterFragmentViewModel(@NonNull Application application) {
        super(application);
        timeTitle.setValue(application.getString(R.string.common_get_vcode));
    }

    public void clearPhoneNum(){
        phoneNum.setValue("");
    }

    public void countDown(Activity activity, View view, String title, int type){
        if(downTimer != null){
            return;
        }
        if(!CheckUtil.orPhoneNumber(phoneNum.getValue())){
            ToastUtils.showShort(R.string.common_check_email);
            return;
        }
        initTimeString = title;
        downTimer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                view.setBackgroundResource(R.drawable.common_btn_pressed);
                timeTitle.setValue(millisUntilFinished / 1000 + "S");
            }

            @Override
            public void onFinish() {
                view.setBackgroundResource(R.drawable.common_btn_normal);
                timeTitle.setValue(initTimeString);
                downTimer.cancel();
                downTimer = null;
            }
        };
        getVCode(activity, type, new IOperationResult() {
            @Override
            public void onSuccess() {
                downTimer.start();
            }

            @Override
            public void onFail() {

            }
        });

    }

    @Override
    protected void onCleared() {
        if (null != downTimer){
            downTimer.cancel();
            downTimer = null;
        }
        if(null != disposable && !disposable.isDisposed()){
            disposable.dispose();
            disposable = null;
        }
        super.onCleared();
    }


//    /**
//     *  修改密码
//     * @param activity
//     * @param operationResult
//     */
//    public void updataPassword(Activity activity, IOperationResult operationResult){
//        if(!CheckUtil.orPhoneNumber(phoneNum.getValue()) ){
//            ToastUtils.showShort(R.string.common_check_email);
//            return;
//        }
//
//        if(!CheckUtil.isVcodeOk(vCode.getValue())){
//            ToastUtils.showShort(R.string.common_check_vcode);
//            return;
//        }
//
//        if(!CheckUtil.isPasswordOk(password.getValue())){
//            ToastUtils.showShort(R.string.common_check_password);
//            return;
//        }
//        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
//        UpdataPasswordBean bean = new UpdataPasswordBean(phoneNum.getValue(), vCode.getValue(), password.getValue());
//        disposable = EasyHttp.post(UrlApi.URL.UpdataPassword.getUrl())
//                .headers("token", token)
//                .cacheMode(CacheMode.NO_CACHE)
//                .upJson(JsonUtil.toJson(bean))
//                .execute(new ProgressDialogCallBack<TipsBean>(LoadingDialog.getProgressDialog(activity)) {
//                    @Override
//                    public void onTokenExpire() {
//                        dismissProgress();
//                        ToastUtils.showShort(R.string.common_login_first);
//                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", false).greenChannel().navigation();
//                    }
//
//                    @Override
//                    public void onError(ApiException e) {
//                        dismissProgress();
//                        ToastUtils.showShort(e.getMessage());
//                        if(null != operationResult){
//                            operationResult.onFail();
//                        }
//                    }
//
//                    @Override
//                    public void onSuccess(TipsBean bean) {
//                        dismissProgress();
//                        if(null != operationResult){
//                            operationResult.onSuccess();
//                        }
//                    }
//                });
//    }

    /**
     *
     * 验证手机号
     * @param activity
     * @param operationResult
     */
    public void checkPhone(Activity activity, IOperationResult operationResult){
        if(!CheckUtil.orPhoneNumber(phoneNum.getValue()) ){
            ToastUtils.showShort(R.string.common_check_email);
            return;
        }
        if(!CheckUtil.isVcodeOk(vCode.getValue())){
            ToastUtils.showShort(R.string.common_check_vcode);
            return;
        }
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        VCodeLoginBean bean = new VCodeLoginBean(phoneNum.getValue(), vCode.getValue());
        disposable = EasyHttp.post(UrlApi.URL.BindCheckPhone.getUrl())
                .headers("token", token)
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(bean))
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        ToastUtils.showShort(e.getMessage());
                        if(null != operationResult){
                            operationResult.onFail();
                        }
                    }

                    @Override
                    public void onSuccess(BaseStringBean bean) {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_success);
                        if(null != operationResult){
                            operationResult.onSuccess();
                        }
                    }
                });
    }

    /**
     * 更改绑定
     * @param activity
     * @param operationResult
     */
    public void bingdingPhone(Activity activity, IOperationResult operationResult){
        if(!CheckUtil.orPhoneNumber(phoneNum.getValue()) ){
            ToastUtils.showShort(R.string.common_check_email);
            return;
        }
        if(!CheckUtil.isVcodeOk(vCode.getValue())){
            ToastUtils.showShort(R.string.common_check_vcode);
            return;
        }
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        VCodeLoginBean bean = new VCodeLoginBean(phoneNum.getValue(), vCode.getValue());
        disposable = EasyHttp.post(UrlApi.URL.ReBindingPhone.getUrl())
                .headers("token", token)
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(bean))
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        ToastUtils.showShort(e.getMessage());
                        if(null != operationResult){
                            operationResult.onFail();
                        }
                    }

                    @Override
                    public void onSuccess(BaseStringBean bean) {
                        dismissProgress();
                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.LOGIN_EMAIL, phoneNum.getValue());
                        ToastUtils.showShort(R.string.common_success);
                        if(null != operationResult){
                            operationResult.onSuccess();
                        }
                    }
                });
    }


    public void getVCode(Activity activity, int type, IOperationResult operationResult){
        String vCodeType = "";
//        if(type == UserAdapterFragment.OPEN_TYPE_RESET_PASSWORD){
//            vCodeType = VerificationBean.ActionType.UpdataPassWord.getValue();
//
//        }else if(type == UserAdapterFragment.OPEN_TYPE_CHECK_PHONE){
//            vCodeType = VerificationBean.ActionType.BindCheck.getValue();
//
//        } else if(type == UserAdapterFragment.OPEN_TYPE_BIND_PHONE){
//            vCodeType = VerificationBean.ActionType.BindPhone.getValue();
//
//        }else if(type == UserAdapterFragment.OPEN_TYPE_DEL_LOGIN_DEV){
//            vCodeType = VerificationBean.ActionType.DelDev.getValue();
//        }
        if(TextUtils.isEmpty(vCodeType)){
            return;
        }
        VerificationBean bean = new VerificationBean(phoneNum.getValue(), vCodeType);
        EasyHttp.post(UrlApi.URL.Verification.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(bean))
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        //登录界面不做处理
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        ToastUtils.showShort(e.getMessage());
                        if(null != operationResult){
                            operationResult.onFail();
                        }
                    }

                    @Override
                    public void onSuccess(BaseStringBean s) {
                        dismissProgress();
                        if(null != operationResult){
                            operationResult.onSuccess();
                        }
                    }
                });
    }
}
